# -*- coding: utf-8 -*-
import os
import os.path
import json
import uuid
import time
import random
import string
import hashlib
import urllib
import copy
from functools import partial
import logging
import pprint


import tornado
import tornado.web
import tornado.escape
import tornado.websocket
import tornado.httpclient
import tornado.gen

from setting import settings
from setting import conn

from datetime import datetime


from base import WebRequest
from base import WebSocket


logger = logging.getLogger(__name__)

from nomagic.cache import get_user, get_users, update_user, get_doc, get_docs, update_doc


"""
data model
"""
from group_m import group_m

class DateEncoder(json.JSONEncoder ):  
    def default(self, obj):  
        if isinstance(obj, datetime):  
            return obj.__str__()  
        return json.JSONEncoder.default(self, obj)  

class NewGroupHandler(WebRequest):
    def post(self):
        
        data = json.loads(self.request.body)

        current_user_id = data["g_uuid"]

        if not current_user_id:
            return

        #add to db
        group_model = group_m()
        data['current_user_id'] = current_user_id;
        group_model.add_group(data)

        self.finish()


class CancelGroupHandler(WebRequest):
    def post(self):

        current_user_id = data["g_uuid"]

        if not current_user_id:
            return

        #add to db
        group_model = group_m()
        data = json.loads(self.request.body)
        data['current_user_id'] = current_user_id;
        group_model.disable_group(data)

        self.finish({})


class GetGroupHandler(WebRequest):
    def post(self):

        group_model = group_m()
        data      = json.loads(self.request.body)
        group_res = group_model.get_group(data)

        print json.dumps(group_res, cls=DateEncoder)

        self.finish(json.dumps(group_res, cls=DateEncoder))


class GetOneGroupHandler(WebRequest):
    def post(self):

        group_model = group_m()
        data      = json.loads(self.request.body)
        group_res = group_model.get_one_group(data)

        print json.dumps(group_res, cls=DateEncoder)

        self.finish(json.dumps(group_res, cls=DateEncoder))

class GetMyGroupHandler(WebRequest):
    def post(self):
        data = json.loads(self.request.body)

        current_user_id = data["g_uuid"]

        if not current_user_id:
            return

        #get from db
        group_model = group_m()
        data['current_user_id'] = current_user_id;
        group_res = group_model.get_my_group(data)

        print json.dumps(group_res, cls=DateEncoder)

        self.finish(json.dumps(group_res, cls=DateEncoder))

